<template>
  <view class="expense-list">
    <view v-if="expenses.length === 0" class="empty-state">
      <wd-icon name="warn-bold" size="48px" color="#ccc"></wd-icon>
      <text class="empty-text">暂无支出记录</text>
    </view>

    <view v-else>
      <!-- 按日期分组显示 -->
      <view v-for="(group, date) in groupedExpenses" :key="date" class="expense-group">
        <view class="date-header">
          <text class="date-text">{{ formatDateHeader(date) }}</text>
          <text class="date-total">¥{{ formatAmount(getDayTotal(group)) }}</text>
        </view>

        <wd-swipe-action v-for="expense in group" :key="expense.id" class="expense-item-wrapper" :before-close="beforeClose">
          <view class="expense-item" @click="viewExpense(expense)">
            <view class="expense-icon">
              <expense-category-icon :icon-name="expense.category"></expense-category-icon>
            </view>
            <view class="expense-info">
              <view class="expense-description">{{ expense.description }}</view>
              <view class="expense-category">{{ getCategoryName(expense.category) }}</view>
            </view>
            <view class="expense-amount">¥{{ formatAmount(expense.amount) }}</view>
          </view>

          <template #right>
            <view class="swipe-actions">
              <view class="action-button edit" @click="editExpense(expense)">
                <wd-icon name="edit" size="20px"></wd-icon>
              </view>
              <view class="action-button delete" @click="deleteExpense(expense)">
                <wd-icon name="delete" size="20px"></wd-icon>
              </view>
            </view>
          </template>
        </wd-swipe-action>
      </view>
    </view>
  </view>
</template>

<script>
import { EXPENSE_CATEGORIES } from "../stores/expense.js";
import ExpenseCategoryIcon from "./ExpenseCategoryIcon.vue";

export default {
  name: "ExpenseList",
  components: {
    ExpenseCategoryIcon,
  },
  props: {
    expenses: {
      type: Array,
      default: () => [],
    },
  },
  computed: {
    // 按日期分组
    groupedExpenses() {
      const groups = {};

      this.expenses.forEach((expense) => {
        const date = new Date(expense.date);
        const dateKey = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, "0")}-${String(date.getDate()).padStart(2, "0")}`;

        if (!groups[dateKey]) {
          groups[dateKey] = [];
        }

        groups[dateKey].push(expense);
      });

      // 对日期进行排序（降序）
      const sortedGroups = {};
      Object.keys(groups)
        .sort((a, b) => new Date(b) - new Date(a))
        .forEach((key) => {
          sortedGroups[key] = groups[key];
        });

      return sortedGroups;
    },
  },
  methods: {
    viewExpense(expense) {
      this.$emit("view", expense);
    },

    editExpense(expense) {
      this.$emit("edit", expense);
    },

    deleteExpense(expense) {
      this.$emit("delete", expense);
    },

    beforeClose({ position, instance }) {
      if (position === "right") {
        instance.close();
      }
    },

    formatAmount(amount) {
      return amount.toFixed(2);
    },

    formatDateHeader(dateStr) {
      const date = new Date(dateStr);
      const today = new Date();
      const yesterday = new Date(today);
      yesterday.setDate(yesterday.getDate() - 1);

      // 格式化为年月日
      const year = date.getFullYear();
      const month = date.getMonth() + 1;
      const day = date.getDate();

      // 判断是否是今天或昨天
      if (date.toDateString() === today.toDateString()) {
        return `今天 (${month}月${day}日)`;
      } else if (date.toDateString() === yesterday.toDateString()) {
        return `昨天 (${month}月${day}日)`;
      } else {
        return `${year}年${month}月${day}日`;
      }
    },

    getCategoryName(categoryId) {
      const category = EXPENSE_CATEGORIES.find((c) => c.id === categoryId);
      return category ? category.name : "未分类";
    },

    getDayTotal(expenses) {
      return expenses.reduce((total, expense) => total + expense.amount, 0);
    },
  },
};
</script>

<script setup>
// Vue 3 setup script
</script>

<style lang="scss" scoped>
.expense-list {
  margin-top: 10px;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px 0;

  .empty-text {
    margin-top: 16px;
    font-size: 16px;
    color: #999;
  }
}

.expense-group {
  margin-bottom: 20px;
}

.date-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 15px;
  background-color: #f0f0f0;
  border-radius: 8px;
  margin-bottom: 10px;

  .date-text {
    font-size: 14px;
    color: #666;
    font-weight: 500;
  }

  .date-total {
    font-size: 14px;
    color: #ff8c00;
    font-weight: 500;
  }
}

.expense-item-wrapper {
  margin-bottom: 10px;
}

.expense-item {
  display: flex;
  align-items: center;
  padding: 15px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.expense-icon {
  margin-right: 12px;
  width: 36px;
  height: 36px;
  border-radius: 50%;
  background-color: #f5f5f5;
  display: flex;
  align-items: center;
  justify-content: center;
}

.expense-info {
  flex: 1;
  overflow: hidden;

  .expense-description {
    font-size: 16px;
    font-weight: 500;
    margin-bottom: 4px;
    color: #333;
  }

  .expense-category {
    font-size: 14px;
    color: #666;
  }
}

.expense-amount {
  font-size: 16px;
  font-weight: 500;
  color: #ff8c00;
}

.swipe-actions {
  display: flex;
  height: 100%;
}

.action-button {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 50px;
  height: 100%;
  color: #fff;

  &.edit {
    background-color: #2196f3;
  }

  &.delete {
    background-color: #ff5252;
  }
}
</style>
